package com.qiu.greened.ui.main

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import com.qiu.greened.R
import com.qiu.greened.adapter.PostAdapter
import com.qiu.greened.databinding.FragmentFollowBinding
import com.qiu.greened.ui.my.LoginActivity
import com.qiu.greened.ui.my.RegisterActivity
import com.qiu.greened.ui.post.PostAddActivity
import com.qiu.greened.utils.MyData
import com.qiu.greened.utils.showToast
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class FollowFragment : Fragment() {

    private val viewModel: FollowViewModel by viewModels()
    private var _binding: FragmentFollowBinding? = null
    private val binding get() = _binding!!
    private val postAdapter by lazy { PostAdapter() }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentFollowBinding.inflate(inflater, container, false)
        val root: View = binding.root
        setHasOptionsMenu(true)
        val linearLayoutManager = LinearLayoutManager(context)
        binding.recyclerView.layoutManager = linearLayoutManager
        binding.recyclerView.adapter = postAdapter
        //触发 Paging 3 分页功能
        lifecycleScope.launch {
            viewModel.getPagingData().collect { pagingData ->
                postAdapter.submitData(pagingData)
            }
        }
        var hasRefreshing = false
        postAdapter.addLoadStateListener {
            binding.swipeRefresh.isRefreshing = it.prepend is LoadState.Loading
            when (it.refresh) {
                is LoadState.NotLoading -> {
                    binding.progressBar.visibility = View.INVISIBLE
                    binding.recyclerView.visibility = View.VISIBLE
                    if (hasRefreshing) {
//                        linearLayoutManager.scrollToPositionWithOffset(0, 0)
                        hasRefreshing = false
                    }
                }
                is LoadState.Loading -> {
                    binding.progressBar.visibility = View.VISIBLE
                    binding.recyclerView.visibility = View.INVISIBLE
                }
                is LoadState.Error -> {
                    val state = it.refresh as LoadState.Error
                    binding.progressBar.visibility = View.INVISIBLE
                    Toast.makeText(
                        activity, "Load Error: ${state.error.message}", Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
        binding.swipeRefresh.setOnRefreshListener {
            hasRefreshing = true
            postAdapter.refresh()
        }
        return root
    }

    override fun onResume() {
        super.onResume()
        activity?.title = "关注"
    }


    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.post_list_menu, menu)
    }
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.add) { //监听菜单按钮
            if (login()) startActivity(Intent(context, PostAddActivity::class.java))
        }
        return super.onOptionsItemSelected(item)
    }

    private fun login(): Boolean {
        var i = false
        if (MyData.login) {
            i = true
        } else {
            "尚未登录，请登录".showToast()
            startActivity(Intent(context, LoginActivity::class.java))
        }
        return i
    }




    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}